/*
 * thread.c
 *
 *  Created on: 2013-4-17
 *      Author: root
 */
#include "thread.h"

/* create_control_thread - 创建控制云台的线程
 *@ return
 */
int create_control_thread(){
	pthread_t tid = 0;
	tid = pthread_create(&tid, NULL, control, NULL);
	if (tid == -1) {
		printf("create control thread failed!\n");
		return -1;
	}
	return tid;
}

int get_menu() {
	int choice = 0;
	while (1) {
		printf("---------------\n");
		printf("1. left\n");
		printf("2. right\n");
		printf("3. up\n");
		printf("4. down\n");
		printf("5. quit\n");
		printf("---------------\n");
		printf("choice : ");
		scanf("%d", &choice);
		if (choice >0 && choice < 6) {
			break;
		} else {
			scanf("%c*[^\n]");
			scanf("%*c");
			printf("Input error, try again...\n");
		}
	}
	return choice;
}

/* control -控制云台
*/
void *control(void *id) {
	int cfd = -1;
	int direction = 0;
 	char *get ;
 	char *stop = "/moveptz.xml?dir=stop";
 	char *host = "192.168.1.198:33";
 	char request[256] = {};
	pthread_detach(pthread_self());
	cfd = connect_server("192.168.1.198", 33);
	if (cfd == -1) {
		printf("control: connect to server failed.\n");
		return (void*)-1;
	}
 	printf("You can chose the direction num to control.\n");

 	while (1) {
 		direction = get_menu();
 		switch (direction) {
 			case 1:get = "/moveptz.xml?dir=left";break;
 			case 2:get = "/moveptz.xml?dir=right";break;
 			case 3:get = "/moveptz.xml?dir=up";break;
 			case 4:get = "/moveptz.xml?dir=down";break;
 			case 5:exit(0);
 			default: break;
 		}
 		//send direction
 		mkrequest(request, 256, get, host);
 		direction = send(cfd, request, strlen(request), 0);
 		if (direction != strlen(request)) {
 			printf("Send request error!\n");
 			continue;
 		}
 		// send stop
 		mkrequest(request, 256, stop, host);
		direction = send(cfd, request, strlen(request), 0);
 		if (direction != strlen(request)) {
 			printf("Send stop request error!\n");
 			continue;
 		}
 	}
 	return (void*)0;
}



